# coding=utf-8
import json

import jsonpickle
from decimal import Decimal
from datetime import  datetime, time, date
from application import app


def bytes_to_obj(json_bytes):
    json_str = json_bytes.decode("utf-8")
    json_obj = json.loads(json_str, encoding='utf-8')
    return json_obj


def value_handler (key,value) :
    if type(value) == Decimal:
        value = float(value)
    if type(value) == datetime:
        value = str(value)
    if type(value) == date:
        value = str(value)
    if type(value) == time:
        value = str(value)
    if "image" in key:
        value = app.config["APP"]["domain"] + app.config["UPLOAD"]["prefix_path"] + value
    return value


def model_to_json(model, keywords) :
    """
    实体类转Json
    :param model:
    :param keywords:
    :return:
    """
    data = {}
    model_dict = model.__dict__
    for key in keywords:
        if key in model_dict :
            data[key] = value_handler(key, model_dict[key])
    return data


def mlist_to_json(model_list, keywords) :
    """
    实体类列表转Json
    :param model_list:
    :param keywords:
    :return:
    """
    data_list = []
    for model in model_list :
        model_json = model_to_json(model, keywords)
        if model_json :
            data_list.append(model_json)
    return data_list


def list_to_json(data_list, keywords, models) :
    """
    非实体类列表转Json
    :param list:
    :param keywords:
    :return:
    """
    data_json = []
    for item in data_list :
        data = {}
        for index in range(len(keywords)) :
            model_json = model_to_json(item[index], keywords[index])
            data[models[index]] = model_json
        data_json.append(data)
    return data_json


def mongo_list_to_json(model_list, keywords) :
    """
    实体类列表转Json
    :param model_list:
    :param keywords:
    :return:
    """
    data_list = []
    for model in model_list :
        model_json = mongo_model_to_json(model, keywords)
        if model_json :
            data_list.append(model_json)
    return data_list


def mongo_model_to_json(model, keywords) :
    """
    实体类转Json
    :param model:
    :param keywords:
    :return:
    """
    data = {}
    for key in keywords:
        if key in model :
            data[key] = value_handler(key, model[key])
    return data


def JsonpickleEncode(obj):
    json_str = jsonpickle.encode(obj)
    json_obj = json.loads(json_str, encoding='utf-8')
    del json_obj["py/object"]
    # json_str = json.dumps(json_obj, ensure_ascii=False)
    return json_obj


def JsonpickleEncodeToRedis(obj):
    json_str = jsonpickle.encode(obj)
    json_obj = json.loads(json_str, encoding='utf-8')
    del json_obj["py/object"]
    json_str = json.dumps(json_obj, ensure_ascii=False)
    return json_str
